using Godot;
using System;

public partial class ExperienceManager : Node
{
	[Signal] 
	public delegate void ExperienceUpdatedEventHandler(int currentExperience,int targetExperience);
	[Signal]
	public delegate void LevelUpEventHandler(int newLevel);

	private int currentExperience = 0;//当前经验
	private int currentLevel = 1;//当前等级
	private int targetExperience = 1;//升级经验

	private const int TARGET_EXPERIENCE_GROWTH = 5;

	GameEvents gameEvents;



	// Called when the node enters the scene tree for the first time.
	public override void _Ready()
	{
		gameEvents = GetNode<GameEvents>("/root/GameEvents");
		gameEvents.ExperienceVialCollected+= OnExperienceVialCollected;
	}

	// Called every frame. 'delta' is the elapsed time since the previous frame.
	public override void _Process(double delta)
	{
	}

	public void incrementExperience(int number){
		currentExperience = Math.Min(currentExperience + number, targetExperience);
		this.EmitSignal(nameof(ExperienceUpdated),currentExperience,targetExperience);
		if(currentExperience == targetExperience){ //升级
			currentLevel++;
			GD.Print("当前等级:",currentLevel);
			currentExperience = 0;
			targetExperience += TARGET_EXPERIENCE_GROWTH;
			this.EmitSignal(nameof(ExperienceUpdated),currentExperience,targetExperience);
			this.EmitSignal(nameof(LevelUp),currentLevel);
		}
	}

	public void OnExperienceVialCollected(int number){
		this.incrementExperience(number);
	}

	public override void _ExitTree(){
		//gameEvents 为自动加载类，不会销毁，所以绑定在gameEvents上的事件需要再节点退出的时候也要解除事件
		gameEvents.ExperienceVialCollected-= OnExperienceVialCollected;
		base._ExitTree();
	}
}
